package com.hscm.boss.common.client;

import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.TimeUnit;


@Component
public class RedisClient {

    //StringRedisTemplate 继承了  RedisTemplate
    //String模板类

    private StringRedisTemplate stringRedisTemplate;

    private HashOperations<String, Object, Object> hashOps;

    private ValueOperations<String, String> valOps;

    //初始化操作
    public RedisClient(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
        hashOps = stringRedisTemplate.opsForHash();
        valOps = stringRedisTemplate.opsForValue();
    }
    //定义操作方法

    /**
     * @param key     redis的key
     * @param data
     * @param timeOut 指定超时时间
     */
    public Boolean setHashMap(String key, Map<String, String> data, int timeOut, TimeUnit timeUnit) {

        hashOps.putAll(key, data);

        //设置key的过期时间
        return stringRedisTemplate.expire(key, timeOut, timeUnit);

    }

    public void setHashMap(String key, Map<String, String> data) {
        hashOps.putAll(key, data);
    }

    public String getHashField(String key, String field) {
        return (String) hashOps.get(key, field);
    }

    //String类型方法
    //存
    public void setValue(String key, String value) {
        valOps.set(key, value);
    }

    //取
    public String getValue(String key) {
        return valOps.get(key);
    }

    public Boolean deleteKey(String key) {
        return stringRedisTemplate.delete(key);
    }
}
